﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;

public partial class PurchaseManager : PMSBase
{ 
    private SqlCodeConfig codeConfig;
    string cmdText = "SELECT T.*,A.CodeName AS PurchaseTypeName" + PMSAccess.AppendSql_UserOrg + "  FROM {0} T  LEFT JOIN " + SqlCodeConfig.TableName + " A ON A.CodeValue=T.PurchaseType AND A.Category='" + PMSCodeCategory.PMS_CGLX + "' where 1=1 ";
    protected void Page_Load(object sender, EventArgs e)
    { 
        this.TableName = "IC_PurchaseOrder";
        this.Key = "PurchaseOrderID";
        if (!IsPostBack)
        {
            pnlGrid.Visible = true;
            pnlEdit.Visible = false;
            string sql = string.Format(cmdText+" ORDER BY T.STATUS ASC,CREATETIME DESC", this.TableName);
            FillGirdView(0, sql);
            InitLoadData();
            tbGoodCode.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbGoodCode.ClientID + "',event);");
            if (!string.IsNullOrEmpty(Request["PurchaseOrderID"]))
            {
                btnView_Click(null, e);
            }
        }
        else
        {
            if (pnlEdit.Visible && !string.IsNullOrEmpty(tbGoodCode.Text))
            {
                GoodItems.AddSelectCode(tbGoodCode.Text);
                tbGoodCode.Text = "";
                tbGoodCode.Focus();
            }
            else if (pnlGrid.Visible)
                FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        }
        GoodItems.IsShowPrice = false;
    }
    public void btnSearchGoodCode_Click(object sender, EventArgs e)
    {
        pnlSearchGoodCode.Visible = true;
    }
    private void InitLoadData()
    {  
        codeConfig = new SqlCodeConfig(this.Connection);
        DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_CGLX);
        this.BindDropDownList(S_PurchaseType, ds, true);
        this.BindDropDownList(SS_PurchaseType, ds, true);
        this.BindDropDownList(P_PurchaseType, ds, true);
        ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_CGSOURCE);
        this.BindDropDownList(P_PurchaseSource, ds, true);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        StringBuilder sql = new StringBuilder(string.Format(cmdText, this.TableName));
        if (!string.IsNullOrEmpty(S_PurchaseOrderCode.Text))
        {
            sql.Append(" AND T.PurchaseOrderCode like '%").Append(S_PurchaseOrderCode.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_PurchaseDate.Text))
        {
            sql.Append(" AND T.PurchaseDate = '").Append(S_PurchaseDate.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(S_PurchaseType.SelectedValue))
        {
            sql.Append(" AND T.PurchaseType = '").Append(S_PurchaseType.SelectedValue).Append("'");
        }
        sql.Append(" ORDER BY T.STATUS ASC,T.CREATETIME DESC");
        FillGirdView(0, sql.ToString());
    }
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "cmdText"] = cmdText;
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    } 
    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }
    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "PurchaseManager.aspx?PurchaseOrderID=" + ((HiddenField)e.Row.Cells[0].Controls[1]).Value;
            e.Row.Cells[2].Text = this.ParseDateToShort(e.Row.Cells[2].Text);
            e.Row.Cells[7].Text = OrderStatus.GetName(e.Row.Cells[7].Text);
        } 
    }
    private void ResetComponent()
    {
        this.ClearPrexControlValues(this.DefaultPrex);
        hfPurchaseOrderID.Value = string.Empty;
        pnlSearchGoodCode.Visible = false;
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
        btnSearchGoodCode.Visible = true;
    } 
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        hfAddOrEdit.Value = "Add";
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = true;
        btnSave.Visible = true;
        SetReadOnly(this.DefaultPrex,false);
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;
        ResetComponent();
        P_PurchaseDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        DataSet ds = PMSAccess.GetDataSet(this.Connection,"select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds;
        GoodItems.IsReadOnly = false;
        GoodItems.GoodCountCaption = "采购数量";
        GoodItems.InitData("IC_PurchaseOrderItem", "PurchaseOrderItemID", "PurchaseOrderID", hfPurchaseOrderID.Value);
    }


    protected void btnRemove_Click(object sender, EventArgs e)
    {
        string purchaseOrderID = Request.Form["PurchaseOrderID"];
        if (string.IsNullOrEmpty(purchaseOrderID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        DataSet ds = PMSAccess.GetDataSet(this.TableName, this.Key, purchaseOrderID);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow dr = ds.Tables[this.TableName].Rows[0];
        int status = Convert.ToInt32(dr["Status"]);
        if (status == OrderStatus.IsStockIn)
        {
            Alert("您选择的采购单已经入库，不能再进行操作！");
            return;
        }
        else if (status == OrderStatus.IsAudited)
        {
            Alert("您选择的采购单已经审核，不能再进行操作！");
            return;
        }
        base.WriteLog("采购单", "删除采购单'" + purchaseOrderID + "'!",
            LogType.Warning, this.GetType().ToString());
        PMSAccess.RemoveDataRow(this.TableName, this.Key, purchaseOrderID);
        PMSAccess.RemoveDataRow("IC_PurchaseOrderItem", this.Key, purchaseOrderID);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }


    protected void btnEdit_Click(object sender, EventArgs e)
    {
        string purchaseOrderID = Request.Form["PurchaseOrderID"];
        if (string.IsNullOrEmpty(purchaseOrderID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        } 
        hfAddOrEdit.Value = "Edit";
        hfPurchaseOrderID.Value = purchaseOrderID;
        string sql = string.Format(cmdText + " AND T.PurchaseOrderID='" + purchaseOrderID + "'", this.TableName);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql,this.TableName);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow dr = ds.Tables[this.TableName].Rows[0];
        int status = Convert.ToInt32(dr["Status"]);
        if (status == OrderStatus.IsStockIn)
        {
            Alert("您选择的采购单已经入库，不能再进行操作！");
            return;
        }
        else if (status == OrderStatus.IsAudited)
        {
            Alert("您选择的采购单已经审核，不能再进行操作！");
            return;
        } 
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = true;
        btnSave.Visible = true;
        btnSearchGoodCode.Visible = true;

        SetReadOnly(this.DefaultPrex, false);
        P_LoginName.ReadOnly = true;
        P_Department.ReadOnly = true;

        SessionManager.DataSet = ds;
        this.FillValueByPrexFromDataRow(dr, this.DefaultPrex);
        P_LoginName.Text = dr["UserName"].ToString();
        P_Department.Text = dr["OrgName"].ToString(); 
        GoodItems.IsReadOnly = false;
        GoodItems.GoodCountCaption = "采购数量";
        GoodItems.InitData("IC_PurchaseOrderItem", "PurchaseOrderItemID", "PurchaseOrderID", purchaseOrderID);
    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        string purchaseOrderID = Request.Form["PurchaseOrderID"];
        if (sender == null)
            purchaseOrderID = Request["PurchaseOrderID"];
        if (string.IsNullOrEmpty(purchaseOrderID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        hfAddOrEdit.Value = "View";
        hfPurchaseOrderID.Value = purchaseOrderID;

        string sql = string.Format(cmdText + " AND T.PurchaseOrderID='" + purchaseOrderID + "'", this.TableName);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql, this.TableName);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow dr = ds.Tables[this.TableName].Rows[0]; 
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;

        btnSelect.Visible = false;
        btnSave.Visible = false;
        btnSearchGoodCode.Visible = false;
        SetReadOnly(this.DefaultPrex, true);

        SessionManager.DataSet = ds;
        this.FillValueByPrexFromDataRow(dr, this.DefaultPrex);
        P_LoginName.Text = dr["UserName"].ToString();
        P_Department.Text = dr["OrgName"].ToString(); 
        GoodItems.IsReadOnly = true;
        GoodItems.GoodCountCaption = "采购数量";
        GoodItems.InitData("IC_PurchaseOrderItem", "PurchaseOrderItemID", "PurchaseOrderID", purchaseOrderID);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hfAddOrEdit.Value == "Add" || hfAddOrEdit.Value == "AddCommon")
        {
            ExecuteAdd(); 
        }
        else
        {
            ExecuteEdit();
        }
    }

    private void ExecuteAdd()
    {
        if (GoodItems.PreProcessSave())
        {
            string orderId = System.Guid.NewGuid().ToString();
            DataRow dr = SessionManager.DataSet.Tables[this.TableName].NewRow();
            dr["PurchaseOrderID"] = orderId;
            dr["PurchaseOrderCode"] = PMSAccess.GetCode(EnumCodeKind.CaiGou);
            dr["Status"] = OrderStatus.WaitProcess;
            hfPurchaseOrderID.Value = orderId;
            this.FillDataRowByPrex(ref dr, this.DefaultPrex, EnumOperator.ADD);
            dr["LoginName"] = SessionManager.UserID;
            dr["Department"] = SessionManager.OrgID; 
            SessionManager.DataSet.Tables[this.TableName].Rows.Add(dr);
            if (hfAddOrEdit.Value == "AddCommon")
            {
                DataTable dt = SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].Copy();
                SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].Clear();
                DataRow dr2 = null;
                foreach (DataRow _dr in dt.Rows)
                {
                    dr2 = SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].NewRow();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        dr2[dc.ColumnName] = _dr[dc.ColumnName];
                    }
                    dr2["PurchaseOrderItemID"] = System.Guid.NewGuid().ToString();
                    dr2["PurchaseOrderID"] = orderId;
                    SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].Rows.Add(dr2);
                }

            }
            else
            {
                foreach (DataRow _dr in SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].Rows)
                {
                    _dr["PurchaseOrderID"] = orderId;
                }
            }
            PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_PurchaseOrder", "IC_PurchaseOrderItem" }, SessionManager.DataSet);
            ResetComponent();
            SessionManager.DataSet.Tables.Remove("IC_PurchaseOrderItem");
            //GoodItems.InitData("IC_PurchaseOrderItem", "PurchaseOrderItemID", "PurchaseOrderID", hfPurchaseOrderID.Value);
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            pnlEdit.Visible = false;
            pnlGrid.Visible = true;
            base.Alert("新建成功");
        }
    } 
    private void ExecuteEdit()
    {
        if (GoodItems.PreProcessSave())
        {
            DataRow dr = SessionManager.DataSet.Tables[this.TableName].Rows[0];
            this.FillDataRowByPrex(ref dr, this.DefaultPrex, EnumOperator.EDIT);
            dr["LoginName"] = SessionManager.UserID;
            dr["Department"] = SessionManager.OrgID; 
 
            PMSAccess.UpdateDataSet(this.Connection, new string[] { "IC_PurchaseOrder", "IC_PurchaseOrderItem" }, SessionManager.DataSet);
            base.Alert("修改成功");
        }
    }

    public void btnSelect_Click(object sender, EventArgs e)
    {
        if (GoodItems.OnSelect != null)
            GoodItems.OnSelect(sender, e);
    }
    public void btnCommonPurchase_Click(object sender, EventArgs e)
    {
        hfAddOrEdit.Value = "AddCommon";
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        GoodItems.ItemsClear();
        GoodItems.IsShowPrice = false;
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select * from " + this.TableName + " where 1=2 ", this.TableName);
        SessionManager.DataSet = ds;

        StringBuilder sql = new StringBuilder(string.Format("SELECT T.*,A.CodeName AS PurchaseTypeName,TU.UserName as UserName,ORG.Subject as OrgName FROM {0} T LEFT JOIN T_User TU on TU.UserId=T.loginName LEFT JOIN T_OrgPool ORG on ORG.OrgId=T.Department LEFT JOIN " + SqlCodeConfig.TableName + " A ON A.CodeValue=T.PurchaseType AND A.Category='" + PMSCodeCategory.PMS_CGLX + "' ", "IC_PurchaseOrder"));
        sql.Append(" WHERE 1=1  and T.CommonName is not null and T.CommonName <>'' and T.Status='" + OrderStatus.WaitProcess + "' ");
        if (!string.IsNullOrEmpty(SS_PurchaseOrderCode.Text))
        {
            sql.Append(" AND T.PurchaseOrderCode like '%").Append(SS_PurchaseOrderCode.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(SS_PurchaseDate.Text))
        {
            sql.Append(" AND T.PurchaseDate = '").Append(SS_PurchaseDate.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(SS_PurchaseType.SelectedValue))
        {
            sql.Append(" AND T.PurchaseType = '").Append(SS_PurchaseType.SelectedValue).Append("'");
        }
        sql.Append(" ORDER BY T.CREATETIME DESC");
        FillPurchaseGridView(0, sql.ToString());
        hfModalPopup.Value = "SelectItem";
        literalModalPopup.Text = "常用采购单";
        purchaseGridView.Visible = true;
        modalPopup.Show(); 
    }

    public void btnExportPurchase_Click(object sender, EventArgs e)
    {
        string PurchaseOrderID = Request["PurchaseOrderID"];
        if (string.IsNullOrEmpty(PurchaseOrderID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".xls");
        string outinfo = DocumentHelper.ExportPurchaseInfo(PMSConst.PMSPurchaseInfoTemplatePath, filePath, PurchaseOrderID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("采购单信息.") + DateTime.Now.ToString("MMdd.HHmmss") + ".xls";
            //base.DownLoadFile(filePath, "采购单信息.xls");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000);
        }

    }

    #region 常用采购单

    protected void btnPurchaseSearch_Click(object sender, EventArgs e)
    {
        StringBuilder sql = new StringBuilder(string.Format("SELECT T.*,A.CodeName AS PurchaseTypeName,TU.UserName as UserName,ORG.Subject as OrgName FROM {0} T LEFT JOIN T_User TU on TU.UserId=T.loginName LEFT JOIN T_OrgPool ORG on ORG.OrgId=T.Department LEFT JOIN " + SqlCodeConfig.TableName + " A ON A.CodeValue=T.PurchaseType AND A.Category='" + PMSCodeCategory.PMS_CGLX + "'", "IC_PurchaseOrder"));
        sql.Append(" WHERE 1=1 and T.CommonName is not null and T.CommonName <>'' and T.Status='" + OrderStatus.WaitProcess + "' ");
        if (!string.IsNullOrEmpty(SS_PurchaseOrderCode.Text))
        {
            sql.Append(" AND T.PurchaseOrderCode like '%").Append(SS_PurchaseOrderCode.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(SS_PurchaseDate.Text))
        {
            sql.Append(" AND T.PurchaseDate = '").Append(SS_PurchaseDate.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(SS_PurchaseType.SelectedValue))
        {
            sql.Append(" AND T.PurchaseType = '").Append(SS_PurchaseType.SelectedValue).Append("'");
        }
        sql.Append(" ORDER BY T.CREATETIME DESC");
        FillPurchaseGridView(0, sql.ToString());
        hfModalPopup.Value = "SelectItem";
        literalModalPopup.Text = "常用采购单";
        purchaseGridView.Visible = true;
        modalPopup.Show();
    }
    protected void FillPurchaseGridView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "purchasecmdText"].ToString();
        }
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        //成功查询出数据后缓存
        ViewState[this.ClientID + "purchasecmdText"] = cmdText;
        purchaseGridView.ShowFooter = true;
        purchaseGridView.NavigationData = splitPage.GetNavigationData(currentPage);
        purchaseGridView.DataSource = ds.Tables[0];
        purchaseGridView.DataBind(); 
    }
    protected void purchaseGridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillPurchaseGridView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "purchasecmdText"].ToString());
    }
    protected void purchaseGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "PurchaseManager.aspx?PurchaseOrderID=" + ((HiddenField)e.Row.Cells[0].Controls[1]).Value;
            e.Row.Cells[8].Attributes.Add("onclick","return confirm('确认要删除吗？');");
        }
    }
    protected void purchaseGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ID = (purchaseGridView.Rows[e.RowIndex].Cells[0].Controls[1] as HiddenField).Value;
        string sql = "update IC_PurchaseOrder set CommonName='' where PurchaseOrderID='" + ID + "'";
        PMSAccess.ExecuteNonQuery(this.Connection,sql);
        FillPurchaseGridView(0,"");
    }
    protected void btnModalPopupOK_Click(object sender, EventArgs e)
    { 
        string orderId = Request["PurchaseOrderID"];
        if (string.IsNullOrEmpty(orderId))
        {
            base.Alert("请选择常用采购单");
            modalPopup.Show();
            return;
        }
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select * from IC_PurchaseOrder where PurchaseOrderID='" + orderId + "'");
        DataRow dr = ds.Tables[0].Rows[0];
        this.FillValueByPrexFromDataRow(dr, this.DefaultPrex);
        P_PurchaseDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        P_LoginName.Text = SessionManager.Username;
        P_Department.Text = SessionManager.OrgName;
        P_CommonName.Text = "";
        GoodItems.IsReadOnly = false;
        GoodItems.GoodCountCaption = "采购数量";
        GoodItems.InitData("IC_PurchaseOrderItem", "PurchaseOrderItemID", "PurchaseOrderID", orderId); 
    }
    #endregion

}
